package com.cz.fra.android.logic;

import java.util.ArrayList;

import com.cz.fra.android.data.FishReport.Picture;
import com.cz.fra.android.entity.Image;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

public class PictureLogic {

	private static PictureLogic instance;
	
	private ContentResolver cr;

	private Context mContext;
	
	private PictureLogic(Context context) {
		mContext = context;
		cr = mContext.getContentResolver();
	}
	
	public static PictureLogic getInstance(Context context) {
		if (instance == null) {
			instance = new PictureLogic(context);
		}
		return instance;
	}
	
	public synchronized void insertPictures(ArrayList<Image> list) {
		if (cr == null) {
			cr = mContext.getContentResolver();
		}

		int length = list.size();
		Log.e("insertImageList start", System.currentTimeMillis() + "");
		ContentValues[] values = new ContentValues[length];
		for (int i = 0; i < length; i++) {
			Image r = list.get(i);
			values[i] = r.instanceToCV();
		}
		cr.bulkInsert(Picture.CONTENT_URI, values);
		synchronized (list) {
			list.clear();
		}
		Log.e("insertImages end", System.currentTimeMillis() + "");
	}
	
	public Image getImage(int reportId){
		if (cr == null) {
			cr = mContext.getContentResolver();
		}
		Cursor cursor = cr.query(Picture.CONTENT_URI, null, Picture.REPORT_ID+ "=" + "'" + reportId+ "'", null, null);
		Image image = new Image();
		if (cursor.moveToFirst()) {
			image.setImagePath(cursor.getString(cursor.getColumnIndex(Picture.PICTURE_URL)));
			image.setReportId(cursor.getInt(cursor.getColumnIndex(Picture.REPORT_ID)));
			image.setUserId(cursor.getInt(cursor.getColumnIndex(Picture.USER_ID)));
			image.setBinaryPic(cursor.getString(cursor.getColumnIndex(Picture.PICTURE_DATA)));
		}
		cursor.close();
		return image;
	}
	
	public ArrayList<Image> getImageList(int reportId){
		if (cr == null) {
			cr = mContext.getContentResolver();
		}
		Cursor cursor = cr.query(Picture.CONTENT_URI, null, Picture.REPORT_ID+ "=" + "'" + reportId+ "'", null, null);
		ArrayList<Image> imageList = new ArrayList<Image>();
		if (cursor.moveToFirst()) {
			do{
				Image image = new Image();
				image.setImagePath(cursor.getString(cursor.getColumnIndex(Picture.PICTURE_URL)));
				image.setReportId(cursor.getInt(cursor.getColumnIndex(Picture.REPORT_ID)));
				image.setUserId(cursor.getInt(cursor.getColumnIndex(Picture.USER_ID)));
				image.setBinaryPic(cursor.getString(cursor.getColumnIndex(Picture.PICTURE_DATA)));
				
				imageList.add(image);
			}while (cursor.moveToNext());
		}
		cursor.close();
		return imageList;
	}
}
